﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace ProjectModule
{
    [XmlInclude(typeof(ProjectSetting))]
    public class ProjectSetting
    {
        public string ProjectName
        {
            get;
            set;
        }
        public double SingleProductGlueTime
        {
            get;
            set;
        }
        public ProjectSetting()
        {
            ProjectName = "";

        }

        public static ProjectSetting Load()
        {
            ProjectSetting pDoc;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ProjectSetting));
            FileStream fsReader = null;
            try
            {
                fsReader = File.OpenRead(Application.StartupPath + @"/MuduleParameter/ProjectSetting" + ".xml");
                pDoc = (ProjectSetting)xmlSerializer.Deserialize(fsReader);
                fsReader.Close();
            }
            catch (IOException)
            {
                if (fsReader != null)
                {
                    fsReader.Close();
                }
                pDoc = new ProjectSetting();

            }
            catch (Exception)
            {
                if (fsReader != null)
                {
                    fsReader.Close();
                }
                pDoc = new ProjectSetting();


            }
            if (pDoc.ProjectName == "")
            {
                FormProjectNameInput formProjectNameInput = new FormProjectNameInput();
                formProjectNameInput.ShowDialog();
                pDoc.ProjectName = formProjectNameInput.ProjectName;
                if (!Directory.Exists(Application.StartupPath + @"/ProjectSetting/"+ pDoc.ProjectName+@"/"))
                {
                    Directory.CreateDirectory(Application.StartupPath + @"/ProjectSetting/" + pDoc.ProjectName + @"/");
                }
                pDoc.Save();
            }
            return pDoc;
        }
        public bool Save()
        {
            if (!Directory.Exists(Application.StartupPath + @"/MuduleParameter/"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"/MuduleParameter/");
            }
            FileStream fsWriter = new FileStream(Application.StartupPath + @"/MuduleParameter/ProjectSetting" + ".xml", FileMode.Create, FileAccess.Write, FileShare.Read);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ProjectSetting));
            xmlSerializer.Serialize(fsWriter, this);
            fsWriter.Flush(true);
            fsWriter.Close();

            return true;
        }
    }
}
